import Alamofire
import Foundation
import Combine


struct Action:Decodable{
    var actionId: Int
    var actionName: String
    var actionImgs: String
    var actionUrl: String
    var duration:String
    var intro: String
    var size: Double
}

struct  Course1:Decodable{
    var courseId: Int
    var courseName: String
    var backgroundUrl: String
    var bodyPart: String
    var degree: String
    var duration: String
    var hits: Int
    var createTime: String
    var calorie: Int
    var courseIntro: String
    var actionList:[Action1]
}

class VideoCacheModel: ObservableObject{
    @Published var actionList:[Action1] = []
    @Published var relatedId : Int = 2
    @Published var downloadSize: Double = 0
    @Published var completeloadSize: Double = 0{
        didSet{
            if(completeloadSize == totalSize){
                complete = true
            }
        }
    }
    @Published var totalSize: Double = 0
    @Published var complete : Bool = false
    
    let queue = OperationQueue()
    var cancellable: Cancellable?
    
    var root : URL{
        return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
            .appendingPathComponent(
                    "Motion",
                    isDirectory: false
            )
    }
    
    //根据课程ID获得动作列表
    func fetchActionListAndDownloadVideo(){
        let headers: HTTPHeaders = [
           "Content-Type": "application/json"
       ]
        
        let parameters = [
            "courseId": relatedId,
        ]
        
        let request = AF.request("https://www.fastmock.site/mock/318b7fee143da8b159d3e46048f8a8b3/api/getActionCounts"
                       ,method: .get
                       ,parameters: parameters
                       ,encoding: URLEncoding.default
                       ,headers: headers
                        )
            //该如何使用
        request.responseDecodable(of: ResponseData<Course1>.self) { (response) in
            print(response)
            guard let res = response.value else { return }

            switch res.status {
                case .success:
                    //获得actionList
                    self.actionList = res.data.actionList
                    //获得视频的大小
                    self.getTotalSize()
                    //将视频保存到本地
                    self.loadVideoIntoLocal()
                    
                    print("self.actionList=\(self.actionList)")
                    
                case .failed:
                    print("faild")
            }
        }
    }
    
    func getTotalSize(){
        for action in actionList {
            totalSize += action.size
        }
        print("totalSize+=\(totalSize)")
    }
    //创建路径
    func creatFilePath(path:String){
        if (IsfileExists(path: path)) {return}
        let fileManager = FileManager.default
        
        do{
            try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        } catch{
            print("create false")
        }
        
    }
    //判断路径是否存在
    func IsfileExists(path:String) ->Bool{

        let  fileManager = FileManager.default
        let result = fileManager.fileExists(atPath: path)

        if result {
            return true
        }else{
            return false
        }
        
    }
    
    func loadVideoIntoLocal(){
        //创建根目录
        creatFilePath(path: root.path)
       
        for action in actionList {
            let cachedPath = root
                .appendingPathComponent(
                    "action_\(action.actionId).mp4",
                    isDirectory: false
                )
            print("cachedPath=\(cachedPath)")
            //对于每一个action来说，如果对应的视频已经在本地中存在，则在已经下载的downloadSize里面加入该视频的大小
            if(IsfileExists(path: cachedPath.path)) {
                downloadSize += action.size
                completeloadSize += action.size
                continue
            }
            
            //如果没有则下载到本地
            let operation = DownloadOperation(session: URLSession.shared, downloadTaskURL: URL(string: action.actionUrl)!, completionHandler: { (localURL, response, error) in
                do {
                    if FileManager.default.fileExists(atPath: cachedPath.path) {
                        try FileManager.default.removeItem(at: cachedPath)
                    }
                    
                    try FileManager.default.copyItem(
                        at: localURL!,
                        to: cachedPath
                    )
                }
                catch _ {
                    print("hasFileError")
                }
            })
            
            cancellable = operation.task.progress.publisher(for: \.fractionCompleted)
                        .sink(){observationProgress in
                            DispatchQueue.main.async {
                                self.downloadSize = self.completeloadSize + action.size * observationProgress
                                if(observationProgress >= 1.0){
                                    self.completeloadSize += action.size
                                }
                            }
                            
                        }
            queue.addOperation(operation)
        }
        
    }
}
